package com.woniu.adapter;

import com.woniu.inlet.web.vo.UserFixedAndCurrentVo;
import com.woniu.outlet.client.FinancePayFeign;
import com.woniu.outlet.client.FinanceUsercenterFeign;
import com.woniu.outlet.mysql.dao.FixedCurrentIncomeDao;
import com.woniu.outlet.mysql.po.FixedCurrentIncomeMySQL;
import com.woniu.outlet.mysql.po.FixedCurrentIncomeMySQLExample;
import com.woniu.service.domain.FixedOrCurrentBuyDto;
import com.woniu.service.domain.UserFixedAndCurrentDto;
import com.woniu.utils.DateUtil;
import com.woniu.utils.NumberRegexValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@Transactional
public class FixedCurrentIncomeAdapter {

    @Autowired
    private FixedCurrentIncomeDao dao;

    @Autowired
    private FinanceUsercenterFeign usercenterFeign;

    @Autowired
    private ProductSellAdapter sellAdapter;

    /**
     * 产品当天买入，即开始算收益。
     * 首先判断买入的是定期还是活期。
     * 活期，是否已买入过该类型产品，本金总额进行累加。收益每天18点进行确认
     * 定期，再生成一条记录。
     * @param dto
     */
    public void insert(FixedOrCurrentBuyDto dto){
        FixedCurrentIncomeMySQL mySQL=new FixedCurrentIncomeMySQL();
        BeanUtils.copyProperties(dto,mySQL);
        mySQL.setStartDate(DateUtil.getSendDate());
        mySQL.setHoldDay(1);
        if(dto.getProductType().equals("fixed")){
            mySQL.setTotalPrincipal(new BigDecimal(dto.getBuyAmount().toString()));
            //定期收益，算最后的收益 本金*收益率
            BigDecimal income=mySQL.getTotalPrincipal().multiply(dto.getRateOfReturn().divide(new BigDecimal("100"),5,BigDecimal.ROUND_HALF_UP));
            mySQL.setIncome(income);
            dao.insertSelective(mySQL);
            log.debug("存入定期收益");
        }else{
            //先查询该用户是否购买了当前活期产品
            FixedCurrentIncomeMySQLExample example=new FixedCurrentIncomeMySQLExample();
            FixedCurrentIncomeMySQLExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(dto.getUserId());
            criteria.andCodeIdEqualTo(dto.getCodeId());
            List<FixedCurrentIncomeMySQL> lists = dao.selectByExample(example);
            if(lists.size()==0){//生成记录
                mySQL.setTotalPrincipal(new BigDecimal(dto.getBuyAmount().toString()));
                mySQL.setIncome(new BigDecimal("0"));
                dao.insertSelective(mySQL);
                log.debug("活期产品不存在，存入活期收益");
            }else{
                FixedCurrentIncomeMySQL oldMySQL = lists.get(0);
                log.debug("活期产品存在，进行追加,原本总金额{},原收益{}",oldMySQL.getTotalPrincipal(),oldMySQL.getIncome());
                BigDecimal totalPrincipal=new BigDecimal(dto.getBuyAmount().toString()).add(oldMySQL.getTotalPrincipal());
                oldMySQL.setTotalPrincipal(totalPrincipal);
                dao.updateByPrimaryKey(oldMySQL);
                log.debug("追加后总金额{}",oldMySQL.getTotalPrincipal());
            }
        }
    }

    /**
     *查询所有活期产品
     * @return
     */
    public List<FixedCurrentIncomeMySQL> getAllCurrent(String date){
        FixedCurrentIncomeMySQLExample example=new FixedCurrentIncomeMySQLExample();
        FixedCurrentIncomeMySQLExample.Criteria criteria = example.createCriteria();
        criteria.andProductTypeEqualTo("current");
        criteria.andStartDateLessThanOrEqualTo(date);
        criteria.andStatusEqualTo(0);
        return dao.selectByExample(example);
    }

    /**
     * 查询所有定期产品
     * @param mySQL
     */
    public List<FixedCurrentIncomeMySQL> getAllFixed(){
        FixedCurrentIncomeMySQLExample example=new FixedCurrentIncomeMySQLExample();
        FixedCurrentIncomeMySQLExample.Criteria criteria = example.createCriteria();
        criteria.andProductTypeEqualTo("fixed");
        criteria.andStatusEqualTo(0);
        return dao.selectByExample(example);
    }

    /**
     * 定期产品到期，自动卖出
     * @param mySQL
     */
    public void autoSellFixed(FixedCurrentIncomeMySQL mysql){
        mysql.setStatus(1);//状态1表示，已卖出
        dao.updateByPrimaryKey(mysql);
    }

    public void updateById(FixedCurrentIncomeMySQL mySQL){
        dao.updateByPrimaryKey(mySQL);
    }

    /**
     * 根据活期产品id,卖出产品，删除活期订单
     * @param currentId
     * @param sellCost
     */
    public FixedCurrentIncomeMySQL sellCurrentProduct(Long currentId) {
        return dao.selectByPrimaryKey(currentId);
    }

    /**
     * 得到用户所有的定期产品
     * @param userId
     * @return
     */
    public UserFixedAndCurrentVo findUserFixedProduct(Long userId) {
        return getUserProductByType(userId,"fixed");
    }

    /**
     * 得到用户所有的活期产品
     * @param userId
     * @return
     */
    public UserFixedAndCurrentVo findUserCurrentProduct(Long userId) {
        return getUserProductByType(userId,"current");
    }

    public UserFixedAndCurrentVo getUserProductByType(Long userId,String type){
        //总资产
        BigDecimal totalAssets=new BigDecimal("0");
        //本金总额
        BigDecimal totalPrincipal=new BigDecimal("0");
        //总收益
        BigDecimal totalIncome=new BigDecimal("0");
        //持有数量
        int totalCount=0;
        List<UserFixedAndCurrentDto> lists=new ArrayList<>();
        FixedCurrentIncomeMySQLExample example=new FixedCurrentIncomeMySQLExample();
        FixedCurrentIncomeMySQLExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andProductTypeEqualTo(type);
        criteria.andStatusEqualTo(0);
        List<FixedCurrentIncomeMySQL> fcs = dao.selectByExample(example);
        if(fcs.size()==0){
            return UserFixedAndCurrentVo.builder()
                    .lists(lists)
                    .totalPrincipal(totalPrincipal)
                    .totalCount(totalCount)
                    .totalIncome(totalIncome)
                    .totalAssets(totalPrincipal.add(totalIncome))
                    .build();
        }
        for (FixedCurrentIncomeMySQL f : fcs) {
            totalPrincipal=totalPrincipal.add(f.getTotalPrincipal());
            totalIncome=totalIncome.add(f.getIncome());
            totalCount++;
            UserFixedAndCurrentDto dto=UserFixedAndCurrentDto.builder()
                    .buyDate(f.getStartDate())
                    .codeId(f.getCodeId())
                    .name(f.getName())
                    .fixedDay(f.getFixedDay())
                    .holdDay(f.getHoldDay())
                    .income(f.getIncome())
                    .rate(f.getRateOfReturn())
                    .totalPrincipal(f.getTotalPrincipal())
                    .build();
            lists.add(dto);
        }

        return UserFixedAndCurrentVo.builder()
                .lists(lists)
                .totalPrincipal(totalPrincipal)
                .totalCount(totalCount)
                .totalIncome(totalIncome)
                .totalAssets(totalPrincipal.add(totalIncome))
                .build();
    }

    /**
     * 得到定期和活期产品的名字
     * @param codeId
     * @return
     */
    public String getName(String codeId) {
        String name="";
        FixedCurrentIncomeMySQLExample example=new FixedCurrentIncomeMySQLExample();
        FixedCurrentIncomeMySQLExample.Criteria criteria = example.createCriteria();
        criteria.andCodeIdEqualTo(codeId);
        List<FixedCurrentIncomeMySQL> fixedCurrentIncomeMySQLS = dao.selectByExample(example);
        for (FixedCurrentIncomeMySQL f : fixedCurrentIncomeMySQLS) {
            name=f.getName();
            break;
        }
        return name;
    }

    public void deleteByPrimaryKey(Long id) {
        dao.deleteByPrimaryKey(id);
    }
}
